#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash scalapack-2.2.0.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1
if [[ "$1" == "$2" ]]; then echo "构建路径与安装路径不能相同，请输入正确的路径"; exit 1; fi

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
set -e

download_pkg()
{
    wget -t 40 -c $1 -O $buildpath/scalapack-2.2.0.tar.gz
    tar xf $buildpath/scalapack-2.2.0.tar.gz -C $buildpath
    #rm -rf $buildpath/scalapack-2.2.0.tar.gz
}

download_pkg https://ghproxy.com/github.com/Reference-ScaLAPACK/scalapack/archive/refs/tags/v2.2.0.tar.gz
cd $buildpath/scalapack-2.2.0
cp SLmake.inc.example SLmake.inc
sed -i -e "s+-lblas+-L$installpath/openblas-0.3.21/lib -lopenblas+g" -e 's+-llapack++g' -e 's+mpif90+mpif90 -fallow-argument-mismatch+g' SLmake.inc
make
mkdir -p $installpath/scalapack-2.2.0/lib
cp libscalapack.a $installpath/scalapack-2.2.0/lib/

cat>"$installpath/scalapack-2.2.0/scalapack_modulefiles"<<EOF
#%Module1.0
conflict scalapack
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set scalapack [getModulefileDir]
setenv SCALAPACK \$scalapack
prepend-path LD_LIBRARY_PATH \$scalapack/lib
EOF

#rm -rf $buildpath/scalapack-2.2.0
